$(function() {
    var curPage = 1;
    var pageSize = 20;
    var uploader;
    var discuccess2 = {
        getList: function() {
			$.ajax({
			    url: wsCommon.host + '/api/memberComments/noShowPicGoods',
			    dataType: wsCommon.jsonType,
				data: {
                    pageSize: pageSize
                },
			    success: function(res) {
					if(res.code == 1) {
						if(res.result) {
							var pager = res.data.pager;

							discuccess2.initPaging(pager.pages, pager.total, res);
						} else {
							wsCommon.setCookie('go_back_link', window.location.href);
							window.location.href = './passport-login.html';
						}
					}
			    },
			    error: function() {
			        // console.log('接口返回失败');
			    }
			})
		},
        initPaging: function(totalPage, totalDataNum, res) {
            var self = this,
                ele = $('[data-role="dirPaging"]');
                if(totalDataNum > 0) {
                    ele.show();
                    var pagination = ele.pagination(totalDataNum, {
                        num_edge_entries: 1,
                        num_display_entries: 4,
                        callback: function(page_index) {
                            if(page_index == 0) {
                                var totalPage = res.data.pager.pages;

                                var pageData = res.data.pager.list;
                                var pager = res.data.pager;
                                discuccess2.randerList(pageData);
                            } else {
                                curPage = page_index + 1;
                                discuccess2.getPageDates();
                            }
                        },
                        items_per_page: pageSize,
                        prev_text: "&lt;&lt;上一页",
                        next_text: "下一页&gt;&gt;",
                        link_to: "javascript:;"
                    });

                }else {
                    ele.hide();
                    $('#member_noshow').html('<p style="text-align: center;line-height: 100px;font-size: 18px;">没有数据</p>')
                }
        },
        getPageDates: function() {
            var self = this;

            $.ajax({
                url: wsCommon.host + '/api/memberComments/noShowPicGoods',
                dataType: wsCommon.jsonType,
                data: {
					pageNum: curPage,
					pageSize: pageSize
				},
                success: function(res) {

                    // 同步页码
                    var totalPage = res.data.pager.pages;

                    var pageData = res.data.pager.list;
                    var pager = res.data.pager;
                    self.randerList(pageData);
                },
                error: function() {
                    // console.log('分页接口失败');
                }
            });
        },
        randerList: function(pageData) {
            var tpl = '<colgroup>\
                            <col class="number-col">\
                            <col class="operate-col">\
                        </colgroup>\
                        <tbody>\
                           <tr class="tr-th">\
                                <th>商品信息</th>\
                                <th>评价状态</th>\
                           </tr>';

            $.each(pageData, function(index, item) {
                var starTpl = '';
                switch (item.point) {
                    case 1:
                        starTpl = '<i class="star1 active" title="一星" _val="1"></i>\
                                    <i class="star2" title="二星" _val="2"></i>\
                                    <i class="star3" title="三星" _val="3"></i>\
                                    <i class="star4" title="四星" _val="4"></i>\
                                    <i class="star5" title="五星" _val="5"></i>';
                        break;
                    case 2:
                        starTpl = '<i class="star1" title="一星" _val="1"></i>\
                                <i class="star2 active" title="二星" _val="2"></i>\
                                <i class="star3" title="三星" _val="3"></i>\
                                <i class="star4" title="四星" _val="4"></i>\
                                <i class="star5" title="五星" _val="5"></i>';
                        break;
                    case 3:
                        starTpl = '<i class="star1" title="一星" _val="1"></i>\
                                <i class="star2" title="二星" _val="2"></i>\
                                <i class="star3 active" title="三星" _val="3"></i>\
                                <i class="star4" title="四星" _val="4"></i>\
                                <i class="star5" title="五星" _val="5"></i>';
                        break;
                    case 4:
                        starTpl = '<i class="star1" title="一星" _val="1"></i>\
                                <i class="star2" title="二星" _val="2"></i>\
                                <i class="star3" title="三星" _val="3"></i>\
                                <i class="star4 active" title="四星" _val="4"></i>\
                                <i class="star5" title="五星" _val="5"></i>';
                        break;
                    case 5:
                        starTpl = '<i class="star1" title="一星" _val="1"></i>\
                                <i class="star2" title="二星" _val="2"></i>\
                                <i class="star3" title="三星" _val="3"></i>\
                                <i class="star4" title="四星" _val="4"></i>\
                                <i class="star5 active" title="五星" _val="5"></i>';
                        break;

                }
                tpl += '<tr class="tr-bd">\
                           <td>\
                               <div class="goods-item">\
                                   <div class="p-img">\
                                       <a target="_blank" href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'">\
                                           <img src="'+item.goodsPic+'" alt="">\
                                       </a>\
                                   </div>\
                                   <div class="p-msg">\
                                       <div class="p-name">\
                                           <a target="_blank" href="./info.html?goodsId='+item.goodsId+'&catId='+item.catId+'">'+item.goodsName+'</a>\
                                           <p style="color:#999;">购买时间：'+item.buyTimeStr+'</p>\
                                       </div>\
                                   </div>\
                               </div>\
                               <div class="goods-number">\
                                       x'+item.buyCount+'\
                               </div>\
                               <div class="clr"></div>\
                           </td>\
                           <td>\
                             <a href="javascript:void(0);" target="_blank" class="btn btn-simple goon_show"><span><span>继续晒单</span></span></a>\
                           </td>\
                        </tr>\
                        <tr class="tr-pj" style="display:none;">\
                          <td colspan="2" class="comt-box">\
                           <div class="form">\
                               <div class="item">\
                                   <span class="label">\
                                       <em>*</em>评分：\
                                   </span>\
                                   <div class="fl">\
                                       <span class="commstar">'+starTpl+'</span>\
                                   </div>\
                               </div>\
                               <div class="item">\
                                   <span class="label">\
                                       <em>*</em>心得：\
                                   </span>\
                                   <div class="fl">\
                                       <div class="summary-cont-box">\
                                           <div class="sumy-tags">\
                                           </div>\
                                           <pre><div class="sumy-area-txt">'+item.commentContent+'</div></pre>\
                                       </div>\
                                   </div>\
                               </div>\
                               <div class="item"  style="display: block; position: relative;">\
                                   <span class="label">晒单：</span>\
                                   <div class="fl">\
                                        <div class="m-imgshow f-imgshow">\
                                           <div class="thumbnail-list" style="position: relative;">\
                                               <div id="fileList'+index+'" class="uploader-list">\
                                               </div>\
                                               <span class="btn-upload" id="upload'+index+'" style="position: relative; z-index: 0;"></span>\
                                               <span class="upload-num">共<em data-role="curnum">0</em>张,还能上传<em data-role="totalnum">10</em>张</span>\
                                           </div>\
                                       </div>\
                                   </div>\
                               </div>\
                               <div class="item">\
                                   <span class="label">\
                                       &nbsp;\
                                   </span>\
                                   <div class="fl">\
                                       <a href="javascript:;" data-role="submit" class="btn btn-simple setcomment" data-orderId="'+item.orderId+'" data-goodsId="'+item.goodsId+'" data-productId="'+item.productId+'" data-commentId="'+item.commentId+'"><span><span>发表评价</span></span></a>\
                                       <input type="checkbox" checked="checked" class="jdcheckbox hide" id="anonymousFlag">\
                                       <label for="anonymousFlag" class="hide">匿名评价</label>\
                                       <span class="wx-share hide">\
                                           <span class="wx-sicon wx-sicon-gray"></span>\
                                           <span class="ftx-03">分享到微信购物圈</span>\
                                       </span>\
                                       <span class="f-stips ml10 hide">首次分享得20京豆</span>\
                                   </div>\
                               </div>\
                           </div>\
                          </td>\
                        </tr>';
            })
            tpl += '</tbody>';
            $('#member_noshow table').html(tpl);

            setTimeout(function() {
                $.each(pageData, function(index, item) {
                    discuccess2.uploadPic(index);
                })
            }, 2000)
        },
        getTabNum: function() {
            $.ajax({
                url: wsCommon.host + '/api/memberComments/count',
                dataType: wsCommon.jsonType,
                success: function(res) {
                    if(res.code == 1) {
                        if(!res.result) {
                            wsCommon.setCookie('go_back_link', window.location.href);
                            window.location.href = './passport-login.html';
                            return;
                        }
                        var data = res.data;
                        if(data.count1 != 0) {
                            $('[data-role="tab1"]').append('<b class="sup">'+data.count1+'</b>');
                        }

                        if(data.count2 != 0) {
                            $('[data-role="tab2"]').append('<b class="sup">'+data.count2+'</b>');
                        }

                        if(data.count3 != 0) {
                            $('[data-role="tab3"]').append('<b class="sup">'+data.count3+'</b>');
                        }
                    } else {
                        iosOverlay({
                            text: res.reason,
                            duration: 1000
                        });
                    }
                },
                error: function(e) {
                }
            })
        },
        // 图片上传
        uploadPic: function(index) {

            // 初始化Web Uploader
            uploader = WebUploader.create({

                // 选完文件后，是否自动上传。
                auto: true,
                // swf文件路径
                swf: './js/Uploader.swf',
                method: 'POST',
                fileVal: 'Filedata',
                // 文件接收服务端。
                server: wsCommon.host + '/api/memberComments/upload',

                // 选择文件的按钮。可选。
                // 内部根据当前运行是创建，可能是input元素，也可能是flash.
                pick: '#upload' + index,
                duplicate: true,
                fileNumLimit: 10,

                // 只允许选择图片文件。
                accept: {
                    title: 'Images',
                    extensions: 'gif,jpg,jpeg,bmp,png',
                    mimeTypes: 'image/jpg,image/jpeg,image/png'
                }
            });

            // 当有文件添加进来的时候
            uploader.on( 'fileQueued', function( file ) {
                var $li = $(
                        '<div id="' + file.id + '" class="file-item thumbnail">' +
                            '<img>' +
                            '<span class="imgdel">删除</span>' +
                        '</div>'
                        ),
                    $img = $li.find('img');


                // $list为容器jQuery实例
                $('#fileList'+index).append( $li );

                // 创建缩略图
                // 如果为非图片文件，可以不用调用此方法。
                // thumbnailWidth x thumbnailHeight 为 100 x 100
                uploader.makeThumb( file, function( error, src ) {
                    if ( error ) {
                        $img.replaceWith('<span>不能预览</span>');
                        return;
                    }

                    $img.attr( 'src', src );
                }, 48, 48 );
            });

            // 文件上传成功，给item添加成功class, 用样式标记上传成功。
            uploader.on( 'uploadSuccess', function( file, res ) {
                $('#' + file.id).attr('data-url', res.url);
                $('#' + file.id).find('.imgdel').attr('data-imgid', file.id);
                var $curnum = $('#' + file.id).closest('.thumbnail-list').find('[data-role="curnum"]');
                $curnum.text(Number($curnum.text()) + 1);
                var $totalnum = $('#' + file.id).closest('.thumbnail-list').find('[data-role="totalnum"]');
                $totalnum.text(Number($totalnum.text()) - 1);
            });
            uploader.on('uploadError', function(file, reason){
                $('#' + file.id).append('<span class="imgtips" style="position:absolute;width:100%;height:20px;line-height:20px;text-align:center;top:0;left:0;background-color:#333;color:#f5f5f5;">上传失败</span>')
            })

            uploader.on('error', function(file, reason){
                if(file == 'Q_EXCEED_NUM_LIMIT') {
                    iosOverlay({
                        text: '最多可上传10个图片',
                        duration: 1000
                    });
                }
            })

        },
        delUploadPic: function() {
			$(document).on('click', '.imgdel', function() {
				if(!$(this).closest('.file-item').find('.imgtips').length) {
					uploader.removeFile( $(this).attr('data-imgid') , true);
					var $curnum = $(this).closest('.thumbnail-list').find('[data-role="curnum"]');
					$curnum.text(Number($curnum.text()) - 1);
					var $totalnum = $(this).closest('.thumbnail-list').find('[data-role="totalnum"]');
					$totalnum.text(Number($totalnum.text()) + 1);
				}
				$(this).closest('.file-item ').remove();
			})
		},
        submit: function() {
            $(document).on('click', '[data-role="submit"]', function() {
                // var hiddenName;
				// if($(this).next('input').prop('checked')) {
				// 	hiddenName = 'YES';
				// } else {
				// 	hiddenName = 'NO';
				// }
                // var obj = {};
                // obj.goodsId = $(this).attr('data-goodsId');
                // obj.productId = $(this).attr('data-productId');
                // obj.orderId = $(this).attr('data-orderId');
                // obj.commentId = $(this).attr('data-commentId');
                // obj.hiddenName = hiddenName;
                var picArr = [];

                $.each($(this).closest('tr').find('.uploader-list').find('.file-item'), function(indexDir, itemDir) {
                    picArr.push($(itemDir).attr('data-url'))
                })
                if(picArr.length == 0) {
                    iosOverlay({
                        text: '请先上传图片',
                        duration: 1000
                    });
                    return;
                }
                // obj.picUrl = picArr.join(',');

                $.ajax({
                    url: wsCommon.host + '/api/memberComments/saveShowPic',
                    dataType: wsCommon.jsonType,
                    data: {
                        goodsId: $(this).attr('data-goodsId'),
                        productId: $(this).attr('data-productId'),
                        orderId: $(this).attr('data-orderId'),
                        commentId: $(this).attr('data-commentId'),
                        picUrl: picArr.join(',')
                    },
                    success: function(res) {
                        if(res.code == 1) {
                            if(!res.result) {
                                wsCommon.setCookie('go_back_link', window.location.href);
                                window.location.href = './passport-login.html';
                                return;
                            }
                            iosOverlay({
                                text: '晒单成功！',
                                duration: 1000,
                                onbeforehide: function() {
                                    window.location.href = './member-nodiscuss_2.html';
                                }
                            });
                        } else {
                            iosOverlay({
                                text: res.reason,
                                duration: 1000
                            });
                        }
                    },
                    error: function(e) {
                    }
                })

            })
        },
        init: function() {
            this.getList();
            this.getTabNum();
            this.delUploadPic();
            this.submit();
        }
    }

    discuccess2.init();
})
